using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using SExperiment;
using SWellPlate;

namespace MainView.Windows
{
	public partial class SubsetEditWindow : Window, IComponentConnector
	{
		public ObservableCollection<Subset> Subsets
		{
			get
			{
				return dataGrid.ItemsSource as ObservableCollection<Subset>;
			}
		}

		public SubsetEditWindow()
		{
			InitializeComponent();
		}

		private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (dataGrid.SelectedIndex == 0)
			{
				btnApplay.IsEnabled = false;
				btnDelete.IsEnabled = false;
			}
			else
			{
				btnApplay.IsEnabled = true;
				btnDelete.IsEnabled = true;
			}
		}

		private void btnAdd_Click(object sender, RoutedEventArgs e)
		{
			if (Subsets != null)
			{
				Subset subset = CreateNewSubset();
				if (subset != null)
				{
					Subsets.Add(subset);
					dataGrid.SelectedItem = subset;
					dataGrid.Focus();
				}
			}
		}

		private void btnDelete_Click(object sender, RoutedEventArgs e)
		{
			if (Subsets != null)
			{
				Subset subset = dataGrid.SelectedItem as Subset;
				if (subset != null)
				{
					Subsets.Remove(subset);
				}
			}
		}

		private void btnApplay_Click(object sender, RoutedEventArgs e)
		{
			Subset subset = dataGrid.SelectedItem as Subset;
			if (subset == null)
			{
				return;
			}
			subset.Wells.Clear();
			foreach (WellCell selectedWell in uCWellPlate.SelectedWells)
			{
				subset.Wells.Add(selectedWell.Well);
			}
			uCWellPlate.SelecteSubset(subset);
		}

		private Subset CreateNewSubset()
		{
			if (Subsets == null)
			{
				return null;
			}
			Subset subset = new Subset();
			int num = 1;
			while (Subsets.Where((Subset s) => s.Name == subset.Name).Count() > 0)
			{
				subset.Name = "Subset " + num++;
			}
			return subset;
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			if (dataGrid.SelectedIndex == -1)
			{
				dataGrid.SelectedIndex = 0;
			}
		}

		private void dataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
		{
			if (e.Row.GetIndex() == 0)
			{
				e.Cancel = true;
			}
		}
	}
}
